#!/usr/bin/env python

#Version histroy
#Ver01 : Initial version
# 

import re
import os
import sys
import glob
import string

ErrorLogFile="Error.log"
ErrorLogFileFH =open (ErrorLogFile,'w')



def RomData2Array(RomDataFile):    
    RomDataFileFH =open(RomDataFile,'rb')
    
    RomDataArray=[]
    #Read RomDataFile and Store in Array by Word format
    while True:
        Temp1 = RomDataFileFH.read(1)
        Temp2 = RomDataFileFH.read(1)
        if Temp1=="" or Temp2=="":
            break
        else:
            #Convert First byte to string
            if Temp1 in string.ascii_letters:
                try:
                    Temp1=str(hex(ord(Temp1)))
                except TypeError:
                    print "Error found in Converting to File! PatternFile: ",PatternFile," RomDataFile: ",RomDataFile,"Counter:",Counter
                    ErrorLogFileFH =open.write()
            elif Temp1 in string.whitespace or Temp1 in string.punctuation:
                Temp1 = str(hex(ord(Temp1)))
            else:
                Temp1 =str(hex(ord(Temp1)))
            #Convert Second byte to string
            if Temp2 in string.ascii_letters:
                try:
                    Temp2=str(hex(ord(Temp2)))
                except TypeError:
                    print "Error found in Converting to File! PatternFile: ",PatternFile," RomDataFile: ",RomDataFile
                    ErrorLogFileFH =open.write()
            elif Temp2 in string.whitespace or Temp2 in string.punctuation:
                Temp2 = str(hex(ord(Temp2)))
            else:
                Temp2 =str(hex(ord(Temp2)))
            #Combin 2 byte to 1 word in string
            if Temp1 <>"" and Temp2 <>"":
                Temp1=Temp1[2:]
                Temp2=Temp2[2:]
                if len(Temp1)<2 :
                    Temp1="".join(("0",Temp1))
                if len(Temp2)<2:
                    Temp2="".join(("0",Temp2))
                    
                RomDataArray.append("".join((Temp1,Temp2)))
        
    return RomDataArray           
    
def CombinRomPattern(PatternFile,RomDataArray,StartAddInPatternFile,StartAddInRomDataFile,ReplaceWordAddress=2):
    if re.search(r'0x',StartAddInPatternFile,re.I):
        pass
    else:
        StartAddInPatternFile="".join(("0x",StartAddInPatternFile))
    StartNumInPatternFile=eval(StartAddInPatternFile)
        
    if re.search(r'0x',StartAddInRomDataFile,re.I):
        pass
    else:
        StartAddInRomDataFile="".join(("0x",StartAddInRomDataFile))
    StartNumInRomData=eval(StartAddInRomDataFile)    
    RomDataArrayLength=len(RomDataArray)
    
    PatternFileFH =open(PatternFile,'r')    
    OutPatternFile="".join((os.path.basename(PatternFile),"_Combin.lp7"))
    if re.search(r".",os.path.basename(PatternFile)):
        Temp=re.split(r"\.",os.path.basename(PatternFile))
        OutPatternFile="".join((Temp[0],"_Combin.lp7"))       
       
    OutPatternFileFH =open(OutPatternFile,'w')        
    PatternLine=re.compile(r'(\|\s+)(\w+)(/)(\w+)(\s+)(\w+)(\s+)(\w+)(\|)(\s+/)(\w+)(,\s+/)(\w+)(,\s+/)(\w+)(.\s+/)(\w+)(,\s+/)(\w+)(,\s+<.+)')    
    for Line in PatternFileFH.readlines():
        #Judge Repeace Rom Data Start Address    
        if PatternLine.search(Line):
            #Replace the ReplaceWordAddress word in Line
            if eval("".join(("0x",PatternLine.search(Line).group(4))))>= StartNumInPatternFile and eval("".join(("0x",PatternLine.search(Line).group(4)))) < StartNumInPatternFile+RomDataArrayLength-StartNumInRomData:
                for Index in range(1,len(PatternLine.search(Line).groups())+1):
                    
                    if Index <> 9+int(ReplaceWordAddress)*2:
                        OutPatternFileFH.write(PatternLine.search(Line).group(Index))
                    else:
                        OutPatternFileFH.write(string.upper(RomDataArray[eval("".join(("0x",PatternLine.search(Line).group(4))))-StartNumInPatternFile+StartNumInRomData/2]))
                    
                OutPatternFileFH.write("\n")        
            else:
                OutPatternFileFH.write(Line)
        else:
            OutPatternFileFH.write(Line)
                
 
if __name__=="__main__":
        
    #RomDataFile="M34518M4-504FP.7r"
    #PatternFile="4519roma.lp7"
    #RomDataArray=RomData2Array(RomDataFile)
    #CombinRomPattern(PatternFile,RomDataArray,"1026","100")
    
    ConfigFile="PatternConfig_MT7300.txt"
    PatternDir=""
    PatternRomFilesArray={}
    PatternFileStartAddArray={}
    RomFileStartAddArray={}
    ReplaceWordAddressAddArray={}
    
    CurrentPath=os.getcwd()
    
    CompiledPatternDir=re.compile(r"(PatternDir=)(\w+.+)")
    CompiledPatternLine=re.compile(r"(PatterFile=)(\w+.+)(,)(RomDataFile=)(\w+.+)(,)(StartAddInPatternFile=)(\w+)(,)(StartAddInRomDataFile=)(\w+)(,)(ReplaceWordAddress=)(\w+)")
    if os.path.isfile(ConfigFile):
        ConvertedRomPath=os.path.join(CurrentPath,"ConvertedRomPattern")
        if os.path.isdir(ConvertedRomPath):
            pass
        else:
            os.mkdir(ConvertedRomPath)
            
        ConfigFileFH=open(ConfigFile,'r')
        for Line in ConfigFileFH.readlines():
            if re.search(r"^#",Line):
                pass
            else:
                if CompiledPatternDir.search(Line):
                    PatternDir=CompiledPatternDir.search(Line).group(2)
                elif CompiledPatternLine.search(Line):
                    if Line[-2]==",":
                        Line=Line[:-2]
                    if len(re.findall(r",",Line))==4:
                        PatternRomFilesArray[CompiledPatternLine.search(Line).group(5)]=CompiledPatternLine.search(Line).group(2)
                        PatternFileStartAddArray[CompiledPatternLine.search(Line).group(5)]=CompiledPatternLine.search(Line).group(8)
                        RomFileStartAddArray[CompiledPatternLine.search(Line).group(5)]=CompiledPatternLine.search(Line).group(11)
                        ReplaceWordAddressAddArray[CompiledPatternLine.search(Line).group(5)]=CompiledPatternLine.search(Line).group(14)
                    else:
                        ErrorLogFileFH.write("Error!,Some Wrong in Configrue File:",ConfigFile,"The Line is :",Line,"!\n")
                        print "Error!,Some Wrong in Configrue File:",ConfigFile,"The Line is :",Line,"!\n"
        for (RomDataFile,PatternFile) in PatternRomFilesArray.items():
            PatternFile=os.path.join(CurrentPath,PatternFile)
            RomDataFile=os.path.join(CurrentPath,RomDataFile)
            
            if os.path.isfile(PatternFile) and os.path.isfile(RomDataFile):
                RomDataArray=RomData2Array(RomDataFile)
                os.chdir(ConvertedRomPath)
                CombinRomPattern(PatternFile,RomDataArray,PatternFileStartAddArray[os.path.basename(RomDataFile)],RomFileStartAddArray[os.path.basename(RomDataFile)],ReplaceWordAddressAddArray[os.path.basename(RomDataFile)])
    else:        
        ErrorLogFileFH.write("Error!,Can't found in dirctory:",CurrentPath,"!\n")
        print "Error!,Can't found in dirctory:",CurrentPath,"!\n"
        
    
    